package com.cx.healthex.client.wechat.controller.common;

import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.ObjectUtils.Null;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.cx.base.apiModel.ApiModel;
import com.cx.base.autoDoc.annotations.AutoDocMethod;
import com.cx.base.autoDoc.annotations.AutoDocType;
import com.cx.base.controller.BaseController;
import com.cx.base.dto.FileUploadDTO;
import com.cx.base.utils.FileUploadUtil;
import com.cx.base.utils.LogInfoUtil;
import com.cx.base.utils.StringUtil;

/**
 * cenxi 2017-01-12
 * */
@RequestMapping("common")
@Controller
@AutoDocType("公共接口")
public class CommonController  extends BaseController{

	@RequestMapping("uploadFile")
	@ResponseBody
	@AutoDocMethod(name = "文件上传",  desc="图片格式限制：gif，jpg，jpeg，png，bmp；语音格式限制：mp3",resClazz = FileUploadDTO.class)
	public ApiModel uploadFile(HttpServletRequest request){
		
		//获取解析器  
        CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
        //判断是否是文件  
        if(resolver.isMultipart(request)){  
            //进行转换  
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)(request);  
            //获取所有文件名称  
            Iterator<String> it = multiRequest.getFileNames();  
            while(it.hasNext()){
                //根据文件名称取文件  
                MultipartFile file = multiRequest.getFile(it.next());
				try {
					FileUploadDTO dto = FileUploadUtil.doUpload(file);
					if (dto == null) {
						return buildErrorMsg(null, DATA_ERROR, "文件上传失败");
					}else{
						if(StringUtil.isNotNull(dto.getError())){
							buildErrorMsg(null, DATA_ERROR, dto.getError());
						}
						return buildSuccMsg(dto);
					}
				} catch (Exception e) {
					LogInfoUtil.error(this.getClass(), "上传图片,出错", e.getMessage(), e);
				}
            }  
        } 
		return buildErrorMsg(null, DATA_ERROR, "文件上传失败");
}
}
